//
//  FindEmoticon.swift
//  正则表达式练习
//
//  Created by 简康达 on 16/6/23.
//  Copyright © 2016年 简康达. All rights reserved.
//

import UIKit
class FindEmoticon {
    static let shareIntance : FindEmoticon = FindEmoticon()
    var manager : PackageManager = PackageManager()
    deinit{
        print("销毁")
    }
    func FindEmoticonWithString(statusText: String,fontHeight : CGFloat) -> NSMutableAttributedString? {
        let attrMStr = NSMutableAttributedString(string: statusText)
        let patten = "\\[.*?\\]"//匹配表情
        //        let patten = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"
        //        创建正则表达式对象
        guard let regex = try? NSRegularExpression(pattern: patten, options: []) else{
            return nil
        }
        //        匹配内容
        let results = regex.matchesInString(statusText, options: [], range: NSRange(location: 0,length: statusText.characters.count))
        //        遍历结果
        for var i = results.count - 1; i >= 0; i -= 1 {
            let result = results[i]
            let chs = (statusText as NSString).substringWithRange(result.range)
            guard let pngPath = findPngPathWithString(chs) else{
                return nil
            }
            let attachment = NSTextAttachment()
            attachment.image = UIImage(contentsOfFile: pngPath)
            attachment.bounds = CGRect(x: 0, y: -3, width: fontHeight, height: fontHeight)
            let attrStr = NSAttributedString(attachment: attachment)
            attrMStr.replaceCharactersInRange(result.range, withAttributedString: attrStr)
        }
        return attrMStr
    }
    func findPngPathWithString(chs : String) -> String? {
        for package in manager.packages {
            for emoticon in package.emoticon {
                if emoticon.chs == chs{
                    return emoticon.pngPath
                }
            }
        }
        return nil
    }
}